<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="utf-8" />
    
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <title>
    Java多线程(线程同步) |  Yolin
  </title>
  <meta name="generator" content="hexo-theme-yilia-plus">
  
  <link rel="shortcut icon" href="/favicon.png" />
  
  
<link rel="stylesheet" href="/css/style.css">

  
<script src="/js/pace.min.js"></script>


  

  

<link rel="alternate" href="/atom.xml" title="Yolin" type="application/atom+xml">
</head>

</html>

<body>
  <div id="app">
    <main class="content">
      <section class="outer">
  <article id="post-Java多线程-线程同步" class="article article-type-post" itemscope
  itemprop="blogPost" data-scroll-reveal>

  <div class="article-inner">
    
    <header class="article-header">
       
<h1 class="article-title sea-center" style="border-left:0" itemprop="name">
  Java多线程(线程同步)
</h1>
  

    </header>
    

    
    <div class="article-meta">
      <a href="/2020/08/16/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E7%BA%BF%E7%A8%8B%E5%90%8C%E6%AD%A5/" class="article-date">
  <time datetime="2020-08-16T07:58:02.000Z" itemprop="datePublished">2020-08-16</time>
</a>
      
  <div class="article-category">
    <a class="article-category-link" href="/categories/Java/">Java</a>
  </div>

      
      
<div class="word_count">
    <span class="post-time">
        <span class="post-meta-item-icon">
            <i class="ri-quill-pen-line"></i>
            <span class="post-meta-item-text"> 字数统计:</span>
            <span class="post-count">1.3k字</span>
        </span>
    </span>

    <span class="post-time">
        &nbsp; | &nbsp;
        <span class="post-meta-item-icon">
            <i class="ri-book-open-line"></i>
            <span class="post-meta-item-text"> 阅读时长≈</span>
            <span class="post-count">5分钟</span>
        </span>
    </span>
</div>

      
    </div>
    

    
    
    <div class="tocbot"></div>





    

    <div class="article-entry" itemprop="articleBody">
      


      

      
      <h2 id="1、-解决多线程安全问题（同步代码块）"><a href="#1、-解决多线程安全问题（同步代码块）" class="headerlink" title="1、 解决多线程安全问题（同步代码块）"></a>1、 解决多线程安全问题（同步代码块）</h2><ul>
<li><p>基本思想：让程序没有安全问题的环境</p>
</li>
<li><p>具体实现：把多条语句操作共享数据的代码给锁起来（Java提供了<strong>同步代码块方式</strong>），让任意时刻只能有一个线程执行即可</p>
</li>
</ul>
<h3 id="1-1-同步代码块"><a href="#1-1-同步代码块" class="headerlink" title="1.1 同步代码块"></a>1.1 同步代码块</h3><p>锁多条语句操作共享数据，可以使用同步代码块实现</p>
<ul>
<li>格式：<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">synchronized</span>(任意对象)&#123;</span><br><span class="line">    <span class="comment">//多条语句操作共享数据的代码</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


</li>
</ul>
<ul>
<li>synchronized(任意对象)：相当于给代码加锁，任意对象就可以看成是一把锁</li>
</ul>
<a id="more"></a>
<h3 id="同步的好处和弊端"><a href="#同步的好处和弊端" class="headerlink" title="同步的好处和弊端"></a>同步的好处和弊端</h3><ul>
<li>好处：解决了多线程的数据安全问题</li>
<li>弊端：当线程很多时，因为每个线程都会去判断同步上的锁，这是很耗费资源的，无形中会降低程序的运行效率</li>
</ul>
<h2 id="2、-售票案例"><a href="#2、-售票案例" class="headerlink" title="2、 售票案例"></a>2、 售票案例</h2><p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-15_12-17-30.jpg" alt=""></p>
<h2 id="3、-解决多线程安全问题（同步代方法）"><a href="#3、-解决多线程安全问题（同步代方法）" class="headerlink" title="3、 解决多线程安全问题（同步代方法）"></a>3、 解决多线程安全问题（同步代方法）</h2><h3 id="3-1-同步方法"><a href="#3-1-同步方法" class="headerlink" title="3.1 同步方法"></a>3.1 同步方法</h3><p>格式：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">修饰符 <span class="keyword">synchronized</span> 返回值类型 方法名（方法参数）&#123; &#125;</span><br></pre></td></tr></table></figure>

<p>同步方法的锁对象是<strong>this</strong></p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-15_13-25-40.jpg" alt=""></p>
<h3 id="3-2-同步静态方法"><a href="#3-2-同步静态方法" class="headerlink" title="3.2 同步静态方法"></a>3.2 同步静态方法</h3><p>格式</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">修饰符 <span class="keyword">static</span> <span class="keyword">synchronized</span> 返回值类型 方法名（方法参数）&#123; &#125;</span><br></pre></td></tr></table></figure>

<p>同步静态方法的锁对象是<strong>类名.class</strong></p>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-15_13-29-55.jpg" alt=""></p>
<h2 id="4、-线程安全的类"><a href="#4、-线程安全的类" class="headerlink" title="4、 线程安全的类"></a>4、 线程安全的类</h2><h3 id="4-1-StringBuffer"><a href="#4-1-StringBuffer" class="headerlink" title="4.1 StringBuffer"></a>4.1 StringBuffer</h3><ul>
<li>线程安全，可变的字符序列</li>
<li>从版本JDK5开始，被StringBuilderder替代。但它更快，因为它不执行同步</li>
</ul>
<h3 id="4-2-Vector"><a href="#4-2-Vector" class="headerlink" title="4.2 Vector"></a>4.2 Vector</h3><ul>
<li>从Java2平台v1.2开始，该类改进了List接口，使其成为Java Collections Framework的成员。与新的集合实现不同，Vector被同步。如果不需要线程安全的实现，建议使用ArrayList代替Vector</li>
</ul>
<h3 id="4-3-Hashtable"><a href="#4-3-Hashtable" class="headerlink" title="4.3 Hashtable"></a>4.3 Hashtable</h3><ul>
<li>该类实现了一个哈希表，它将键映射到值。任何非null对象都可以用作键或者值</li>
<li>从java2平台v1.2开始，该类进行了改进，实现了Map接口，使其成为Java Collections Framework的成员。与新的集合实现不同，Hashtable被同步。如果不需要线程安全的实现，建议使用HashMap代替Hashtable</li>
</ul>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> sellTicket;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.Collections;</span><br><span class="line"><span class="keyword">import</span> java.util.HashMap;</span><br><span class="line"><span class="keyword">import</span> java.util.Hashtable;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"><span class="keyword">import</span> java.util.Vector;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">demo</span> </span>&#123;</span><br><span class="line">	<span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">		StringBuffer sbf=<span class="keyword">new</span> StringBuffer();</span><br><span class="line">		StringBuilder sb=<span class="keyword">new</span> StringBuilder();</span><br><span class="line">		</span><br><span class="line">		Vector&lt;String&gt; v=<span class="keyword">new</span> Vector&lt;String&gt;();</span><br><span class="line">		ArrayList&lt;String&gt; array=<span class="keyword">new</span> ArrayList&lt;String&gt;();</span><br><span class="line">		</span><br><span class="line">		Hashtable&lt;String,String&gt; table=<span class="keyword">new</span> Hashtable&lt;String, String&gt;();</span><br><span class="line">		HashMap&lt;String, String&gt;  map=<span class="keyword">new</span> HashMap&lt;String, String&gt;();</span><br><span class="line">		</span><br><span class="line">		<span class="comment">//将集合包装成线程安全的集合类</span></span><br><span class="line">		List&lt;String&gt; list=Collections.synchronizedList(<span class="keyword">new</span> ArrayList&lt;String&gt;());</span><br><span class="line"> 		</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="5-Lock锁"><a href="#5-Lock锁" class="headerlink" title="5. Lock锁"></a>5. Lock锁</h2><p>为了更清晰表达如何加锁和释放锁，JDK5以后提供了一个新的锁对象Lock</p>
<p>Lock实现提供比使用synchronized方法和语句可以获得更广泛的锁定操作</p>
<p>Lock中提供了获得锁和释放锁的方法</p>
<ul>
<li><strong>void lock()</strong> ：获得锁</li>
<li><strong>void unlock()</strong>：释放锁</li>
</ul>
<p>Lock是接口不能直接实例化，这里采用它的实现类<strong>ReentrantLock</strong>来实例化</p>
<p>ReentrantLock的构造方法</p>
<ul>
<li>ReentrantLock():创建一个ReentrantLock的实例</li>
</ul>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-15_19-35-21.jpg" alt=""></p>
<h2 id="6-生产者消费者模式概述"><a href="#6-生产者消费者模式概述" class="headerlink" title="6. 生产者消费者模式概述"></a>6. 生产者消费者模式概述</h2><p>生产者消费者模式是一个十分经典的多线程协作的模式，弄懂生产者消费者问题能够让我们对多线程编程的理解更加深刻，所谓生产者消费者问题，实际上主要包含了两类线程：</p>
<ul>
<li>一类是<strong>生产者线程用于生产数据</strong></li>
<li>一类是<strong>消费者线程用于消费数据</strong></li>
</ul>
<p><strong><em>为了解耦生产者和消费者的关系，通常会采用共享的数据区域，就像是一个仓库</em></strong></p>
<ul>
<li>生产者生产数据后直接放置在共享的数据区中，并不需要关心消费者的行为</li>
<li>消费者只需要从共享数据区中去获取数据，并不需要关心生产者的行为</li>
</ul>
<blockquote>
<p><strong>生产者—&gt;共享数据区域  &lt;— 消费者</strong></p>
</blockquote>
<p>为了体现生产和消费过程中的等待和唤醒，Java就提供了几个方法供我们使用，这几个方法在Object类中</p>
<p>Object类的等待和唤醒方法：</p>
<table>
<thead>
<tr>
<th>方法名</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>void wait()</td>
<td>导致当前线程等待，直到另一个线程调用该对象的notify()方法或notifyAll()方法</td>
</tr>
<tr>
<td>void notify()</td>
<td>唤醒正在等待对象监视器的单个线程</td>
</tr>
<tr>
<td>void notifyAll()</td>
<td>唤醒正在等待对象监视器的所有线程</td>
</tr>
</tbody></table>
<h2 id="7-生产者消费者案例"><a href="#7-生产者消费者案例" class="headerlink" title="7. 生产者消费者案例"></a>7. 生产者消费者案例</h2><p>案例中包含的类：</p>
<ul>
<li>奶箱类（box）:定义一个成员变量，表示第x瓶奶，提供存储牛奶和获取牛奶的操作</li>
<li>生产者类（Producer）：实现Runnable接口，重写run（）方法，调用存储牛奶的操作</li>
<li>消费者类(Customer):实现Runnable接口，重写run()方法，调用获取牛奶的操作</li>
<li>测试类(BoxDemo):里面有main()方法：<blockquote>
<p>①创建奶箱对象，这是共享数据区域</p>
<p>②创建生产者对象，把奶箱对象作为构造方法参数传递，因为在这个类中要调用存储牛奶的操作</p>
<p>③创建消费者对象，把奶箱对象作为构造方法参数传递，因为在这个类中要调用获取牛奶的操作</p>
<p>④创建两个线程对象，分别把生产者对象和消费者对象作为构造方法参数传递</p>
<p>⑤启动线程</p>
</blockquote>
</li>
</ul>
<p><img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/Snipaste_2020-08-16_15-19-25.jpg" alt=""></p>

      
      <!-- reward -->
      
    </div>
      <!-- copyright -->
      
    <footer class="article-footer">
      
      
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Lock%E9%94%81/" rel="tag">Lock锁</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%90%8C%E6%AD%A5%E4%BB%A3%E7%A0%81%E5%9D%97/" rel="tag">同步代码块</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/%E5%90%8C%E6%AD%A5%E6%96%B9%E6%B3%95/" rel="tag">同步方法</a></li></ul>


    </footer>

  </div>

  
  
  <nav class="article-nav">
    
      <a href="/2020/08/18/%E8%BF%9B%E5%87%BB%E7%9A%84%E7%BD%91%E7%BB%9C%E7%BC%96%E7%A8%8B%EF%BC%88%E4%B8%80%EF%BC%89/" class="article-nav-link">
        <strong class="article-nav-caption">上一篇</strong>
        <div class="article-nav-title">
          
            进击的网络编程（一）
          
        </div>
      </a>
    
    
      <a href="/2020/08/14/Java%E5%A4%9A%E7%BA%BF%E7%A8%8B-%E5%AE%9E%E7%8E%B0%E5%A4%9A%E7%BA%BF%E7%A8%8B/" class="article-nav-link">
        <strong class="article-nav-caption">下一篇</strong>
        <div class="article-nav-title">Java多线程(实现多线程)</div>
      </a>
    
  </nav>


  

  
  
<!-- valine评论 -->
<div id="vcomments-box">
    <div id="vcomments">
    </div>
</div>
<script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src='https://cdn.jsdelivr.net/npm/valine@1.3.10/dist/Valine.min.js'></script>
<script>
    new Valine({
        el: '#vcomments',
        notify: false,
        verify: '',
        app_id: '',
        app_key: '',
        path: window.location.pathname,
        avatar: 'mp',
        placeholder: '给我的文章加点评论吧~',
        recordIP: true
    });
    const infoEle = document.querySelector('#vcomments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0) {
        infoEle.childNodes.forEach(function (item) {
            item.parentNode.removeChild(item);
        });
    }
</script>
<style>
    #vcomments-box {
        padding: 5px 30px;
    }

    @media screen and (max-width: 800px) {
        #vcomments-box {
            padding: 5px 0px;
        }
    }

    #vcomments-box #vcomments {
        background-color: #fff;
    }

    .v .vlist .vcard .vh {
        padding-right: 20px;
    }

    .v .vlist .vcard {
        padding-left: 10px;
    }
</style>

  

  
  
  

</article>
</section>
      <footer class="footer">
  <div class="outer">
    <ul class="list-inline">
      <li>
        &copy;
        2020-2021
        张金
      </li>
      <li>
        
      </li>
    </ul>
    <ul class="list-inline">
      <li>
        
        
        <span>
  <i>PV:<span id="busuanzi_value_page_pv"></span></i>
  <i>UV:<span id="busuanzi_value_site_uv"></span></i>
</span>
        
      </li>
      <li>
        <!-- cnzz统计 -->
        
        <script type="text/javascript" src='https://s9.cnzz.com/z_stat.php?id=1278069914&amp;web_id=1278069914'></script>
        
        <img src="https://yolin121.oss-cn-beijing.aliyuncs.com/blogimg/beian.png">
        <a href="https://beian.miit.gov.cn"  style="color:#f72b07" target="_blank">陕ICP备20002449号</a>
      </li>

    </ul>
  </div>
</footer>
    <div class="to_top">
        <div class="totop" id="totop">
  <i class="ri-arrow-up-line"></i>
</div>
      </div>
    </main>
      <aside class="sidebar">
        <button class="navbar-toggle"></button>
<nav class="navbar">
  
  <div class="logo">
    <a href="/"><img src="/images/ayer-side.svg" alt="Yolin"></a>
  </div>
  
  <ul class="nav nav-main">
    
    <li class="nav-item">
      <a class="nav-item-link" href="/">主页</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/archives">归档</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/categories">分类</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/tags">标签</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/playlist">歌单</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/video">视频</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/about">关于我</a>
    </li>
    
    <li class="nav-item">
      <a class="nav-item-link" href="/friends">友情链接</a>
    </li>
    
  </ul>
</nav>
<nav class="navbar navbar-bottom">
  <ul class="nav">
    <li class="nav-item">
      
      <a class="nav-item-link nav-item-search"  title="Search">
        <i class="ri-search-line"></i>
      </a>
      
      
      <a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
        <i class="ri-rss-line"></i>
      </a>
      
    </li>
  </ul>
</nav>
<div class="search-form-wrap">
  <div class="local-search local-search-plugin">
  <input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
  <div id="local-search-result" class="local-search-result"></div>
</div>
</div>
      </aside>
      <div id="mask"></div>

<!-- #reward -->
<div id="reward">
  <span class="close"><i class="ri-close-line"></i></span>
  <p class="reward-p"><i class="ri-cup-line"></i>请我喝杯咖啡吧~</p>
  <div class="reward-box">
    
    <div class="reward-item">
      <img class="reward-img" src="/images/alipay.jpg">
      <span class="reward-type">支付宝</span>
    </div>
    
    
    <div class="reward-item">
      <img class="reward-img" src="/images/wechat.jpg">
      <span class="reward-type">微信</span>
    </div>
    
  </div>
</div>
      
<script src="/js/jquery-2.0.3.min.js"></script>


<script src="/js/jquery.justifiedGallery.min.js"></script>


<script src="/js/lazyload.min.js"></script>


<script src="/js/busuanzi-2.3.pure.min.js"></script>


<script src="/js/share.js"></script>




<script>
  try {
    var typed = new Typed("#subtitle", {
    strings: ['肠断月明红豆蔻,','月似当时,','人似当时否？'],
    startDelay: 1500,
    typeSpeed: 200,
    loop: true,
    backSpeed: 40,
    showCursor: true
    });
  } catch (err) {
  }
  
</script>




<script src="/js/tocbot.min.js"></script>

<script>
  // Tocbot_v4.7.0  http://tscanlin.github.io/tocbot/
  tocbot.init({
    tocSelector: '.tocbot',
    contentSelector: '.article-entry',
    headingSelector: 'h1, h2, h3, h4, h5, h6',
    hasInnerContainers: true,
    scrollSmooth: true,
    scrollContainer:'main',
    positionFixedSelector: '.tocbot',
    positionFixedClass: 'is-position-fixed',
    fixedSidebarOffset: 'auto',
    onClick: (e) => {
      $('.toc-link').removeClass('is-active-link');
      $(`a[href=${e.target.hash}]`).addClass('is-active-link');
      $(e.target.hash).scrollIntoView();
      return false;
    }
  });
</script>


<script>
  var ayerConfig = {
    mathjax: true
  }
</script>


<script src="/js/ayer.js"></script>


<script src="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/jquery-modal@0.9.2/jquery.modal.min.css">


<!-- Root element of PhotoSwipe. Must have class pswp. -->
<div class="pswp" tabindex="-1" role="dialog" aria-hidden="true">

    <!-- Background of PhotoSwipe. 
         It's a separate element as animating opacity is faster than rgba(). -->
    <div class="pswp__bg"></div>

    <!-- Slides wrapper with overflow:hidden. -->
    <div class="pswp__scroll-wrap">

        <!-- Container that holds slides. 
            PhotoSwipe keeps only 3 of them in the DOM to save memory.
            Don't modify these 3 pswp__item elements, data is added later on. -->
        <div class="pswp__container">
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
            <div class="pswp__item"></div>
        </div>

        <!-- Default (PhotoSwipeUI_Default) interface on top of sliding area. Can be changed. -->
        <div class="pswp__ui pswp__ui--hidden">

            <div class="pswp__top-bar">

                <!--  Controls are self-explanatory. Order can be changed. -->

                <div class="pswp__counter"></div>

                <button class="pswp__button pswp__button--close" title="Close (Esc)"></button>

                <button class="pswp__button pswp__button--share" style="display:none" title="Share"></button>

                <button class="pswp__button pswp__button--fs" title="Toggle fullscreen"></button>

                <button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button>

                <!-- Preloader demo http://codepen.io/dimsemenov/pen/yyBWoR -->
                <!-- element will get class pswp__preloader--active when preloader is running -->
                <div class="pswp__preloader">
                    <div class="pswp__preloader__icn">
                        <div class="pswp__preloader__cut">
                            <div class="pswp__preloader__donut"></div>
                        </div>
                    </div>
                </div>
            </div>

            <div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap">
                <div class="pswp__share-tooltip"></div>
            </div>

            <button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)">
            </button>

            <button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)">
            </button>

            <div class="pswp__caption">
                <div class="pswp__caption__center"></div>
            </div>

        </div>

    </div>

</div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.css">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/default-skin/default-skin.css">
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/photoswipe@4.1.3/dist/photoswipe-ui-default.min.js"></script>

<script>
    function viewer_init() {
        let pswpElement = document.querySelectorAll('.pswp')[0];
        let $imgArr = document.querySelectorAll(('.article-entry img:not(.reward-img)'))

        $imgArr.forEach(($em, i) => {
            $em.onclick = () => {
                // slider展开状态
                // todo: 这样不好，后面改成状态
                if (document.querySelector('.left-col.show')) return
                let items = []
                $imgArr.forEach(($em2, i2) => {
                    let img = $em2.getAttribute('data-idx', i2)
                    let src = $em2.getAttribute('data-target') || $em2.getAttribute('src')
                    let title = $em2.getAttribute('alt')
                    // 获得原图尺寸
                    const image = new Image()
                    image.src = src
                    items.push({
                        src: src,
                        w: image.width || $em2.width,
                        h: image.height || $em2.height,
                        title: title
                    })
                })
                var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, {
                    index: parseInt(i)
                });
                gallery.init()
            }
        })
    }
    viewer_init()
</script>



<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
      tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
  });

  MathJax.Hub.Queue(function() {
      var all = MathJax.Hub.getAllJax(), i;
      for(i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
      }
  });
</script>

<script src="https://cdn.jsdelivr.net/npm/mathjax@2.7.6/unpacked/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>


<script type="text/javascript" src="https://js.users.51.la/20544303.js"></script>
  </div>
</body>

</html>